<?php

namespace common\components\extenders;

use common\components\helpers\Fun;
use common\components\helpers\Tree;
use common\components\helpers\Util;
use common\models\datas\Menu;
use yii\base\BaseObject;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;

class MenuManage extends BaseObject
{

    const SIDEBAR_MENU = '0'; //左侧导航

    const TOP_MENU = '1'; //顶部导航

    const LEFT_MENU = '2'; //左侧导航

    const TOOLBAR = '3'; //工具条

    const BATCH_TOOLBAR = '4'; //批处理工具条

    const RECORD_ITEM_TOOLBAR = '5'; //记录项链接

    private $_disable = [];

    public $position;

    public $data;

    public $currentMenu;

    public $menu_cache;

    public function __construct($position, $data = [])
    {
        parent::__construct();
        $this->position = $position;
        $this->data = $data;
        $id = \Yii::$app->id;
//        Fun::updateCache('menu_branch_cache', false);
        if ($id == 'app-backend') {
            $this->currentMenu = Fun::getCurrentMenu(Fun::cache('menu_main_cache'));
            $this->menu_cache = Fun::cache('menu_main_cache');

        } elseif ($id == 'app-frontend') {
            $this->currentMenu = Fun::getCurrentMenu(Fun::cache('menu_branch_cache', false));
            $this->menu_cache =Fun::cache('menu_branch_cache', false);
        } elseif ($id == 'app-zhtfrontend') {
            $this->currentMenu = Fun::getCurrentMenu(Fun::cache('menu_branch_cache', false));
            $this->menu_cache =Fun::cache('menu_branch_cache', false);
        }

    }

    public function isDisable($params)
    {
        foreach ($params as $k => $v) {
            if (!is_int($v) && !is_string($v)) {
                $this->_disable[$k] = $v;
            }
        }
        return $this;
    }

    public function create()
    {
        switch ($this->position) {
            case self::SIDEBAR_MENU:
                $menuStr = $this->sideBarMenu();
                break;
            case self::TOP_MENU:
                $menuStr = $this->topMenu();
                break;
            case self::LEFT_MENU:
                $menuStr = $this->leftMenu();
                break;
            case self::TOOLBAR:
                $menuStr = $this->toolbar();
                break;
            case self::BATCH_TOOLBAR:
                $menuStr = '';
                break;
            case self::RECORD_ITEM_TOOLBAR:
                $menuStr = $this->recordItemToolbar();
                break;
            default :
                $menuStr = '';
                break;
        }
        return $menuStr;
    }

    private function sideBarMenu($mid=0)
    {
        $arr=[];
        foreach($this->menu_cache as $k=>$m){
            if(\Yii::$app->id == 'app-frontend'){
                unset($this->menu_cache[711]);
            }
            if($m['parent_id']==$mid && $m['position']<=2 && $m['display']!=0){
                if (self::__procesAccess($m)) {

                    $a['label']=$m['name'];
                    if($m['parent_id']==0){
                        $a['url']='#';
                        $a['data-url']='#';
                        //$a['icon']="iconfont icon-sidebar-{$m['id']}";
                        $a['icon'] = "fa fa-fw {$m['icon']}";
                        $a['class'] = '';
                    }else{
                        $class = '';
                        $leftmenu = \Yii::$app->session['leftmenu'];
                        if($leftmenu == $this->getParent($m['id'])){
                            $class = 'active';
                        }
                        $a['icon'] = "fa fa-fw {$m['icon']}";
                        $a['data-url']=$m['m'] . '/' . $m['c'];
                        $a['class'] = $class;
                        if(isset($m['m']) && !empty($m['m'])){
                            $a['data-url']='/'.$m['m'] . '/' . $m['c'];
                            $a['url']=Fun::url(ArrayHelper::merge(['/' . $m['m'] . '/' . $m['c'] . '/' . $m['a']], Util::param2array($m['param']) != null ? Util::param2array($m['param']) : []));
                        }else{
                            $a['data-url']= '/' . $m['c'];
                            $a['url']=Fun::url(ArrayHelper::merge(['/' . $m['c'] . '/' . $m['a']], Util::param2array($m['param']) != null ? Util::param2array($m['param']) : []));
                        }
                        //$a['url']=Fun::url(ArrayHelper::merge([$m['m'] . '/' . $m['c'] . '/' . $m['a']], Util::param2array($m['param']) != null ? Util::param2array($m['param']) : []));
                    }
                    $a['items']=$this->sideBarMenu($m['id']);
                    $arr[]=$a;
                }
            }
        }
        return $arr;
    }

    private function getParent($id){
        $model = Menu::findOne($id);
        if($model->position == 2){
            return $model->c.'-'.$model->a;
        }else{
            $this->getParent($model->parent_id);
        }
    }

    private function topMenu()
    {
        if (\Yii::$app->id == 'app-backend') {
            $menuTop = (new Tree(Fun::cache('menu_main_cache')))->get_child(0);
        } else {
            $menuTop = (new Tree(Fun::cache('menu_branch_cache', false)))->get_child(0);
        }
        $toolbar = '';

        foreach ($menuTop as $v) {
            if ($v['position'] != self::TOP_MENU) continue;
            if ($v['parent_id'] != 0 || $v['display'] == 0) continue;
            if (!self::__procesAccess($v)) continue;
            $toolbar .= "<a data-id=\"{$v['id']}\"><span class=\"{$v['icon']}\"></span> {$v['name']}</a>";
        }
        return $toolbar;
    }

    private function leftMenu()
    {
        if (!isset($this->data['id'])) return '';
        if (\Yii::$app->id == 'app-backend') {
            $tree = new Tree(Fun::cache('menu_main_cache'));
        } else {
            $tree = new Tree(Fun::cache('menu_branch_cache', false));
        }
        $menuLeft = $tree->get_child($this->data['id']);
        $menuLeftStr = '';
        foreach ($menuLeft as $k => $v) {
            if ($v['position'] != self::LEFT_MENU) continue;
            if ($v['display'] == 0) continue;
            if (!self::__procesAccess($v)) continue;
            $url = Fun::url(ArrayHelper::merge([$v['m'] . '/' . $v['c'] . '/' . $v['a']], Util::param2array($v['param']) != null ? Util::param2array($v['param']) : []));
            $menuLeftStr .= "<a rel=\"tab-add-iframe\" data-url=\"{$url}\"><span class='icon-left'></span>{$v['name']}</a>";
        }
        return $menuLeftStr;
    }

    private function toolbar()
    {
        if (\Yii::$app->id == 'app-backend') {
            $menuCache = Fun::cache('menu_main_cache');
        } else {
            $menuCache = Fun::cache('menu_branch_cache', false);
        }
        $tree = new Tree($menuCache);
        $menuLevel = $tree->get_level($this->currentMenu['id']);
        $menuList = [];
        if ($menuLevel == 2) {
            $menuList = $tree->get_child($this->currentMenu['id']);
        }
        if (empty($menuList)) return '';
        $menuDialog = 0;
        foreach ($menuList as $k => $v) {
            if ($v['display'] == 2 || $v['display'] == 3) {
                $menuDialog = $k;
                break;
            }
        }
        if ($menuDialog > 0) {
            $menuDialogArray = $menuList[$menuDialog];
            unset($menuList[$menuDialog]);
            $menuList = ArrayHelper::merge([$menuDialogArray['id'] => $menuDialogArray], $menuList);
        }
        $toolbar = [];
        foreach ($menuList as $v) {
            if ($v['position'] == self::RECORD_ITEM_TOOLBAR || $v['position'] == self::BATCH_TOOLBAR) continue;
            if (!self::__procesAccess($v)) continue;
            $toolbar[] = $this->displayMenu($v);
        }
        return !empty($toolbar) ? implode('', array_filter($toolbar)) : '';
    }

    private function recordItemToolbar()
    {
        if (empty($this->data)) return '';
        if (\Yii::$app->id == 'app-backend') {
            $menuCache = Fun::cache('menu_main_cache');
        } else {
            $menuCache = Fun::cache('menu_branch_cache', false);
        }
        $tree = new Tree($menuCache);
        $menuChild = $tree->get_child($this->currentMenu['id']);
        $toolbar = [];
        if(!empty($menuChild) && count($menuChild)>0) {
            foreach ($menuChild as $v) {
                if ($v['position'] != self::RECORD_ITEM_TOOLBAR) continue;
                if (!self::__procesAccess($v)) continue;
                $toolbar[] = $this->displayMenu($v);
            }
        }
        return !empty($toolbar) ? implode('<span>&nbsp;</span>', array_filter($toolbar)) : '';
    }

    private function  __procesAccess($menu)
    {
//        Fun::setSiteDatabases(Fun::getSiteId());
        if (\Yii::$app->user->isGuest) {
            return false;
        } elseif (\Yii::$app->user->identity->role != 'admin' && !\Yii::$app->user->can(Fun::getPermissionStr($menu))) {
            return false;
        } else {
            return true;
        }
    }

    private function displayMenu($menu)
    {
        $disable_key = array_keys($this->_disable);
        switch ($menu['display']) {
            case 0://不显示
                return null;
            case 1://显示
                return ($this->currentMenu['id'] == $menu['id']) ? Html::a('<i class="yx-floatl iconfont icon-add" style="font-size: 70px;color: #fff"></i><h3 class="yx-fn">'.$menu['name'].'</h3>', Fun::createMenuUrl($menu, $this->data), ['class' => 'yx-fn-box yx-bgfeaa85 yx-radius3  yx-floatl']) : Html::a('<i class="yx-floatl  iconfont icon-add"  style="font-size: 70px;color: #fff"></i><h3 class="yx-fn">'.$menu['name'].'</h3>', Fun::createMenuUrl($menu, $this->data),['class' => 'yx-fn-box yx-bgfeaa85 yx-radius3  yx-floatl']);
            case 2://弹窗方式
                $str=\yii\helpers\Html::a('<i class="yx-floatl iconfont icon-add" style="font-size: 70px;color: #fff"></i><h3 class="yx-fn">'.$menu['name'].'</h3>', null, [
                    'id' => "dialog-show-iframe",
                    'rel' => 'dialog-show-iframe',
                    'class' => 'yx-fn-box yx-bgfeaa85 yx-radius3 yx-floatl',
                    'data' => [
                        'options' => 'plain:true,selected:true',
                        'url' => Util::createMenuUrl($menu, $this->data),
                        'name'=>$menu['name'],
                        'size' => $menu['size']
                    ]
                ]);
                if(!empty($this->_disable) && !empty($disable_key) && in_array($menu['a'], $disable_key)){
                    $callback = call_user_func($this->_disable[$menu['a']], $this->data);
                    return !empty($callback) ? $callback : $str;
                }
                return $str;
            case 3://记录项页面方式
                $str=\yii\helpers\Html::a($menu['name'], Util::createMenuUrl($menu, $this->data), [
                    'rel' => 'action-handle',
                    'class' => 'btn yx-radius2 yx-d-card yx-bg94d5a2',
                    'data' => [
                        'options' => 'plain:true,selected:true',
                        'action' => $menu['a'],
                        'params' => [
                            'd' => 'd',
                            'c' => 'c'
                        ]
                    ]
                ]);
                if(!empty($this->_disable) && !empty($disable_key) && in_array($menu['a'], $disable_key)){
                    $callback = call_user_func($this->_disable[$menu['a']], $this->data);
                    return !empty($callback) ? $callback : $str;
                }
                return $str;
            case 4://记录项弹出方式
                $str=Html::a($menu['name'], null, [
                    'rel' => 'dialog-show-iframe',
                    'data' => [
                        'url' => Util::createMenuUrl($menu, $this->data),
                        'name'=>$menu['name'],
                        'size' => $menu['size']
                    ],
                    'class'=>'btn yx-radius2 yx-d-card yx-bg94d5a2'
                ]);
                if(!empty($this->_disable) && !empty($disable_key) && in_array($menu['a'], $disable_key)){
                    $callback = call_user_func($this->_disable[$menu['a']], $this->data);
                    return !empty($callback) ? $callback : $str;
                }
                return $str;
            case 5://记录项Action方式
                $str = Html::a($menu['name'],null, [
                    'rel'=>'record_item_confirm',
                    'data' => [
                        'url' => Util::createMenuUrl($menu, $this->data),
                        'message' => $this->getMessage($menu),

                    ],
                    'class'=>'btn yx-radius2 yx-d-card yx-bgb5b5b5'
                ]);
                if (!empty($this->_disable) && !empty($disable_key) && in_array($menu['a'], $disable_key)) {
                    $callback = call_user_func($this->_disable[$menu['a']], $this->data);
                    return !empty($callback) ? $callback : $str;
                }
                return $str;
            case 6:
                return \yii\helpers\Html::a('<i class="yx-floatl iconfont icon-add" style="font-size: 70px;color: #fff"></i><h3 class="yx-fn">'.$menu['name'].'</h3>',Util::createMenuUrl($menu, $this->data), [
                    'rel' => 'action-handle-batchInput',
                    'class' => 'yx-fn-box yx-bgf9d0e5 yx-radius3  yx-floatl',
                    'data' => [
                        'method'=>'post',
                        'options' => 'plain:true,selected:true',
                        'action' => $menu['a'],
                     ]
                ]);
            case 7:
                return \yii\helpers\Html::a($menu['name'], Util::createMenuUrl($menu, $this->data), [
                    'rel' => 'action-handle-batchSelection',
                    'class' => 'easyui-linkbutton',
                    'data' => [
                        'method'=>'post',
                        'options' => 'plain:true,selected:true',
                        'action' => $menu['a'],
//                        'params' => [
//                            'd' => 'd',
//                            'c' => 'c'
//                        ]
                    ]
                ]);
            case 8://弹窗方式
                $str=\yii\helpers\Html::a('<i class="yx-floatl iconfont icon-sidebar-279" style="font-size: 70px;color: #fff"></i><h3 class="yx-fn">'.$menu['name'].'</h3>', null, [
                    'id' => "dialog-show-iframe",
                    'rel' => 'dialog-show-iframe',
                    'class' => 'yx-fn-box yx-bgfeaa85 yx-radius3 yx-floatl',
                    'data' => [
                        'options' => 'plain:true,selected:true',
                        'url' => Util::createMenuUrl($menu, $this->data),
                        'name'=>$menu['name'],
                        'size' => $menu['size']
                    ]
                ]);
                if(!empty($this->_disable) && !empty($disable_key) && in_array($menu['a'], $disable_key)){
                    $callback = call_user_func($this->_disable[$menu['a']], $this->data);
                    return !empty($callback) ? $callback : $str;
                }
                return $str;
            case 9:
                return \yii\helpers\Html::a('<i class="yx-floatl iconfont icon-sidebar-279" style="font-size: 70px;color: #fff"></i><h3 class="yx-fn">'.$menu['name'].'</h3>',Util::createMenuUrl($menu, $this->data), [
                    'rel' => 'action-handle-batchInput',
                    'class' => 'yx-fn-box yx-bgf9d0e5 yx-radius3  yx-floatl',
                    'data' => [
                        'method'=>'post',
                        'options' => 'plain:true,selected:true',
                        'action' => $menu['a'],
                    ]
                ]);

            default :
                return null;
        }
    }

    private function getMessage($menu)
    {
        if (empty($menu['message'])) return '';

        $message = $menu['message'];
        foreach ($this->data as $k => $v) {
            $message = str_replace('{$' . $k . '}', $v, $message);
        }
        return $message;
    }
//下面是分店后台会员管理部分用到的代码
    public function detailsMenu($controller='',$action = '', $displays,$params = [],$modules='')
    {
        $menustr='';
        $parm = $params;
        $display=$displays;
        if (\Yii::$app->id == 'app-backend') {
            $menu = Fun::cache('menu_main_cache');
        }else{
            $menu=Fun::cache('menu_branch_cache',false);
        }
        $custormer_menu = Fun::getCacheColumn($menu, ['m'=>$modules,'c' =>$controller, 'a' => $action]);
        if(count($custormer_menu)!==1&&!empty($this->data)){
            unset($custormer_menu['322']);
        }
        foreach ($custormer_menu as $v){
            if (!self::__procesAccess($v)) continue;
            $menustr =$this->detailsDisplay($v,$display,$parm);
        }
        return $menustr;
    }

    private function detailsDisplay($menu,$display,$params = [])
    {
        $url_param=!empty($menu['param'])?Util::param2array($menu['param']):[];
        foreach($url_param as $k=>$v){
            if(isset($params['data'][$k])){
                $url_param[$k]=$params['data'][$k];
                unset($params['data'][$k]);
            }
        }
        if(!empty($menu['m'])){
            $mca =   $menu['m'].'/'.$menu['c'] . '/' . $menu['a'];
        }else{
            $mca = $menu['c'] . '/' . $menu['a'];
        }

        $url=Fun::url(ArrayHelper::merge([$mca],$url_param));
        $name = $menu['name'];
        if(isset($params['data']['title']) && !empty($params['data']['title'])){
            $name = $params['data']['title'];
        }
        if($menu['display'] != 0) {
            if ($display) {
                return Html::a($name, $url, $params);
            } else {
                $attr_data = isset($params['data']) ? $params['data'] : [];
                $attr_data['size'] = $menu['size'];
                $attr_data['url'] = $url;
                $params['data'] = $attr_data;
                return Html::a($name, null, $params);
            }
        }else{
            return '';
        }


    }
}